package com.zsk.okhttp;

import okhttp3.OkHttpClient;

/**
 * OkHttpClient is thread safe，It is better to set global uniqueness.As a result, HTTP instances can be used globally
 * 
 * @author keke
 * @date 2020/04/23
 */
public class Http implements IHttp {

    private OkHttpClient client;

    private String baseUrl = "";

    public Http(OkHttpClient client) {
        super();
        this.client = client;
    }

    public static Http of(boolean ignoreSsl) {
        return new Http(HttpFactory.newOkHttpClient(ignoreSsl));

    }

    public static Http of(OkHttpClient client) {
        return new Http(client);
    }

    public String getBaseUrl() {
        return baseUrl;
    }

    public void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    @Override
    public IGetTask get(String url) {
        return new GetTask(client, prepareUrl(url));
    };

    @Override
    public IPostTask post(String url) {
        return new PostTask(client, prepareUrl(url));
    }

    @Override
    public IPostMultiTask postMultiForm(String url) {
        return new PostMultiTask(client, prepareUrl(url));
    }

    @Override
    public IPostTask put(String url) {
        return new PutTask(client, prepareUrl(url));
    }

    @Override
    public IPostTask delete(String url) {
        return new DeleteTask(client, prepareUrl(url));
    }

    /**
     * 预处理url，根据是否设置baseUrl追加根地址
     * 
     * @param url
     * @return
     */
    private String prepareUrl(String url) {
        String httpUrlRegex = "http[s]?[:]?//.*";
        if (baseUrl.length() > 0 && url.matches(httpUrlRegex)) {
            throw new RuntimeException("base url is not empty," + baseUrl + ",url can't start with http");
        }
        return baseUrl + url;
    }

}
